﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Daphne.Modularity.UI
{
    /// <summary>
    /// Class for saving the page state
    /// </summary>
    public class PageState: Dictionary<string, object>
    {
        /// <summary>
        /// Prefix for keys - used for child-controls of the page
        /// </summary>
        public string KeyPrefix
        { get; set; }

        public PageState()
        {
            ClearKeyPrefix();
        }

        /// <summary>
        /// Clear the key-prefix
        /// </summary>
        public void ClearKeyPrefix()
        {
            KeyPrefix = string.Empty;
        }

        /// <summary>
        /// Returns value from the page state
        /// </summary>
        public T Get<T>(string key, T defaultValue = default(T))
        {
            // try to get value from the dictionary
            object objValue;
            if (base.TryGetValue(KeyPrefix + key, out objValue) == false)
                return defaultValue;

            // check the type
            if (!(objValue is T))
                return defaultValue;

            return (T)objValue;
        }

        /// <summary>
        /// Sets the value of page state
        /// </summary>
        public void Set<T>(string key, T value)
        {
            base[KeyPrefix + key] = value;
        }
    }
}
